package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动实例化与当前reflectDemo8在同一个包下被@AutoClass标注的类
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception {
        File dir = new File(ReflectDemo8.class.getResource(
                "."
        ).toURI());

        File[] files = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File file : files) {
            String className = file.getName().substring(0, file.getName().indexOf("."));
            Class cls = Class.forName(ReflectDemo8.class.getPackage().getName() + "." + className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println("实例化：" + className);
                Object o = cls.newInstance();
                System.out.println(o);
                Method[] methods = cls.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int num = arm.value();
                        System.out.println("自动调用方法：" + method.getName() + ":" + num + "次");
                        for (int i = 0; i < num; i++) {
                            method.invoke(o);
                        }

                    }
                }
            }


        }


    }

}
